package ui.activity.order;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.jakewharton.rxbinding.view.RxView;

import net.ck.hzq.PaymentorderActivity;
import net.ck.hzq.R;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import Bean.FindAddressBean;
import activity.SelectAddressAct;
import base.BaseAct;
import butterknife.BindView;
import coom.Constants;
import event.AddressDeleteEvent;
import event.AddressEvent;
import event.AddressRefreshEvent;
import event.NetErrorEvent;
import event.SiteAddressEvent;
import ui.activity.home.UseRedBallAct;
import ui.activity.order.biz.ConfirmOrderBiz;
import ui.activity.order.component.DaggerConfirmOrderComponent;
import ui.activity.order.contract.ConfirmOrderContract;
import ui.activity.order.module.ConfirmOrderModule;
import ui.activity.order.presenter.ConfirmOrderPresenter;
import ui.activity.poscontrol.beanmodel.RedBallnumBean;
import util.StringUtils;


/**
 * 提交订单
 * Created by chenjian on 2017/8/4.
 */

public class ConfirmOrderAct extends BaseAct implements ConfirmOrderContract.View {


    @Inject
    ConfirmOrderPresenter presenter;
    @Inject
    ConfirmOrderBiz biz;

    @BindView(R.id.no_address_layout)
    RelativeLayout noAddressLayout;
    @BindView(R.id.address_name)
    TextView addressName;
    @BindView(R.id.address_phone)
    TextView addressPhone;
    @BindView(R.id.address_info)
    TextView addressInfo;
    @BindView(R.id.address_layout)
    RelativeLayout addressLayout;
    @BindView(R.id.relative_redball)
    RelativeLayout relative_redball;

    @BindView(R.id.confirm_order_image)
    SimpleDraweeView orderImage;
    @BindView(R.id.confirm_order_name)
    TextView orderName;
    @BindView(R.id.confirm_order_price)
    TextView orderPrice;
    @BindView(R.id.confirm_order_number)
    TextView orderNumber;
    @BindView(R.id.redballnum)
    TextView redballnum;
    @BindView(R.id.siteaddresstext)
    TextView siteaddresstext;

    @BindView(R.id.from_address_layout)
    RelativeLayout from_address_layout;

    @BindView(R.id.confirm_order_total_price)
    TextView orderTotalPrice;
    @BindView(R.id.confirm_order)
    Button confirmOrder;

    private String addressId = "";
    private SharedPreferences sp;
    private String id, sellname, price;
    private String address = "";
    private String buyNumber;
    private String totalPrice;
    private String redballid="";
    private int type;//1pos2物料
    private String newTotalPrice;//包含红包的新总价
    private int selecttickid =-1;
    private int tickid=1;

    @Override
    protected void setRoot() {
//        setTitleBar(R.color.colorBlue);
        setContentView(R.layout.activity_confrim_order);
    }

    @Override
    protected void setup() {
        DaggerConfirmOrderComponent.builder().confirmOrderModule(new ConfirmOrderModule(this)).build().inject(this);
        setToolBar(getResources().getString(R.string.lang_confirm_order), "");
        presenter.setBiz(biz);
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        Constants.activitys.add(this);
        sp = getSharedPreferences("ToBuy", Context.MODE_PRIVATE);
        id = StringUtils.isEmpty(getIntent().getStringExtra("id")) ? "" : getIntent().getStringExtra("id");
        sellname = StringUtils.isEmpty(getIntent().getStringExtra("sellName")) ? "" : getIntent().getStringExtra("sellName");
        price = StringUtils.isEmpty(getIntent().getStringExtra("price")) ? "" : getIntent().getStringExtra("price");
        buyNumber = StringUtils.isEmpty(getIntent().getStringExtra("buyNumber")) ? "1" : getIntent().getStringExtra("buyNumber");
        totalPrice = StringUtils.isEmpty(getIntent().getStringExtra("totalPrice")) ? "" : getIntent().getStringExtra("totalPrice");
        newTotalPrice = totalPrice;
        type = getIntent().getIntExtra("type",1);
        orderImage.setImageURI(Uri.parse(StringUtils.isEmpty(getIntent().getStringExtra("pic")) ? "" : getIntent().getStringExtra("pic")));
        orderName.setText(sellname);
        orderNumber.setText(buyNumber);
        orderPrice.setText("¥ " + price);
        Spanned strB = Html.fromHtml("合计金额：<font color=#FF2F2F>" + "¥ " + totalPrice + "</font>");
        orderTotalPrice.setText(strB);
        presenter.getAddressList(sp.getString("id", "0"));
        presenter.getRedballNum(id);
        RxView.clicks(noAddressLayout)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> presenter.toAddress());
        RxView.clicks(addressLayout)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> presenter.toAddress());
        RxView.clicks(relative_redball)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> toSelectRedball());

        RxView.clicks(confirmOrder)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> presenter.toSubmitOrder(buyNumber, id, address, newTotalPrice, addressId,type,selecttickid,siteaddresstext.getText().toString()));

        from_address_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ConfirmOrderAct.this, SelectAddressAct.class);
                startActivity(intent);
            }
        });
    }

    private void  toSelectRedball(){
        Intent intent = new Intent(ConfirmOrderAct.this, UseRedBallAct.class);
//        startActivity(intent);
        intent.putExtra("redballid",redballid);
        intent.putExtra("tickid",redballid);
        startActivityForResult(intent, 113);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 支付返回
        if (requestCode == 112) {
            startAct(OrderAct.class, null);
            if (Constants.activitys.size() > 0) {
                for (Activity act : Constants.activitys) {
                    act.finish();
                }
                Constants.activitys.clear();
            }
        }
        // 选择红包返回
        if (requestCode == 113) {
            if(null!=data) {
                redballid = data.getStringExtra("redballid");
                if (redballid.equals("2")) {
                    redballnum.setText("不使用红包");
                    selecttickid = -1;
                    Spanned strB = Html.fromHtml("合计金额：<font color=#FF2F2F>" + "¥ " + totalPrice + "</font>");
                    newTotalPrice = totalPrice + "";
                    orderTotalPrice.setText(strB);
                    redballnum.setTextColor(Color.parseColor("#333333"));
                } else {
                    selecttickid = data.getIntExtra("id", -1);
                    redballnum.setText("-¥" + data.getStringExtra("redballmoney"));
                    redballnum.setTextColor(Color.parseColor("#FF2F2F"));
                    Double totalprice = Double.parseDouble(totalPrice) - Double.parseDouble(data.getStringExtra("redballmoney"));
                    Spanned strB = Html.fromHtml("合计金额：<font color=#FF2F2F>" + "¥ " + totalprice + "</font>");
                    newTotalPrice = totalprice + "";
                    orderTotalPrice.setText(strB);
                }
            }
        }
    }


    @Override
    public void onNetErrorEvent(NetErrorEvent event) {
        super.onNetErrorEvent(event);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        biz.onDestory();
    }


    @Override
    public void upAddressUI(FindAddressBean.DataBean.ItemsBean bean) {
        if (bean == null) {
            noAddressLayout.setVisibility(View.VISIBLE);
            addressLayout.setVisibility(View.GONE);
        } else {
            noAddressLayout.setVisibility(View.GONE);
            addressLayout.setVisibility(View.VISIBLE);
            addressId = bean.getId();
            addressName.setText("收货人：" + bean.getName());
            addressPhone.setText("电话：" + bean.getPhone());
            addressInfo.setText("收货地址：" + bean.getAddress());
            address = bean.getAddress();
        }
    }

    @Override
    public void upRedballUI(RedBallnumBean bean) {
        int num = 0;
        if(bean.getShopTickets().size()>0){
            relative_redball.setVisibility(View.VISIBLE);
        }
        for (int i =0;i<bean.getUserShopTickets().size();i++){
            num+=bean.getUserShopTickets().get(i).getCount();
        }
        if(num==0){
            redballnum.setText("无可用红包");
            redballnum.setTextColor(Color.parseColor("#333333"));
        }else{
            redballnum.setText(num+"个红包");
            redballnum.setTextColor(Color.parseColor("#FF2F2F"));
        }

    }

    @Override
    public void toPay(String orderId, String price) {
        Intent intent = new Intent(ConfirmOrderAct.this, PaymentorderActivity.class);
        intent.putExtra("id", orderId);
        intent.putExtra("price", price);
        startActivityForResult(intent, 112);
    }

    /**
     * 切换地址
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void registerAddressEvent(AddressEvent event) {
        if (event.getBean() == null) {
            noAddressLayout.setVisibility(View.VISIBLE);
            addressLayout.setVisibility(View.GONE);
        } else {
            noAddressLayout.setVisibility(View.GONE);
            addressLayout.setVisibility(View.VISIBLE);
            addressId = event.getBean().getId();
            addressName.setText("收货人：" + event.getBean().getName());
            addressPhone.setText("电话：" + event.getBean().getPhone());
            addressInfo.setText("收货地址：" + event.getBean().getAddress());
            address = event.getBean().getAddress();
        }
    }
    /**
     * 切换地址
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void siteAddressEvent(SiteAddressEvent event) {
        siteaddresstext.setText(event.getBean());

    }
    /**
     * 删除地址
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void registerAddressDelete(AddressDeleteEvent event) {
        if (!StringUtils.isEmpty(event.getAddressId())) {
            if (addressId.equals(event.getAddressId()))
                noAddressLayout.setVisibility(View.VISIBLE);
            addressLayout.setVisibility(View.GONE);
            addressId = "";
            addressName.setText("");
            addressPhone.setText("");
            addressInfo.setText("");
            address = "";
            presenter.getAddressList(sp.getString("id", "0"));
        }
    }


    /**
     * 默认地址
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void registerAddressDefresh(AddressRefreshEvent event) {
        presenter.getAddressList(sp.getString("id", "0"));
    }

}
